

import { Image, Text, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import * as React from "react";
import type { MutiPictureViewProps } from '../../types/MutiPictureView';


const icon_add_image = require('./icon_add_image.png')
const icon_del_image = require('./icon_del_image.png')


export const MutiPictureView:
    React.FC<MutiPictureViewProps>
    = props => {
        const {
            bind,
            maxCount = 6,
            sourceType = ['album'],
            addIcon,
            addIconStyle,
            // dashed 1px #A3A9CC 
            addIconContainerStyle,//borderWidth: 1, borderStyle: 'dashed', borderColor: assets.color_A3A9CC  虚线框
            delIcon,
            delIconStyle,
            spacingHorizontal = '15px',
            spacingInner = '8px',
            editable = true,
        } = props
        const { viewModel, setViewModel } = bind
        const { photos = [] } = viewModel
        const [sideLength, setSideLength] = React.useState<string>(`0px`)
        const containerRef = React.useRef<HTMLElement>()

        /**
         * @description: 添加照片
         * @return {*}
         */
        const add = () => {
            let images: any[] = viewModel.photos || []
            if (!images) {
                throw new Error("viewModel没有定义photos字段")
            }

            Taro.chooseImage({
                count: maxCount - (viewModel.photos?.length || 0),
                sizeType: ['original', 'compressed'],
                sourceType: sourceType,
                success: (res: MutiPictureViewProps.SuccessCallbackResult) => {
                    // console.log({ res })
                    if (res.tempFiles?.length > 0) {
                        setViewModel({ photos: [...photos, ...res.tempFiles] as MutiPictureViewProps.ImageFile[] | string[] })
                    }
                },
                fail: ((res: {
                    /** 错误信息 */
                    errMsg: string
                }) => {
                    Taro.showToast({ title: res.errMsg || '未知错误', duration: 1000, icon: 'none' })
                })
            })
        }


        /**
         * @description: 按索引删除
         * @param {number} index
         * @return {*}
         */
        const del = (index: number) => {
            photos.splice(index, 1)
            setViewModel({ photos: [...viewModel.photos || []] as MutiPictureViewProps.ImageFile[] | string[] })
        }


        /**
         * @description: 预览
         * @param {number} index
         * @return {*}
         */
         const show = (index: number) => {
            let urls: string[] =  (props.value || photos)?.map(i => typeof (i) == 'string' ? i : i.path)
            Taro.previewImage({
                urls,
                current: urls[index],
            })
        }








        const ItemView:
            React.FC<{ src: string, index: number }>
            = ({ src, index }) => {
                return (
                    <View style={Object.assign({}, styles.item_container, {
                        marginTop: index < 3 ? 0 : spacingInner,
                        marginLeft: index % 3 == 0 ? spacingHorizontal : spacingInner,
                        width: sideLength,
                        height: sideLength,
                    })} onClick={e => {
                        e.stopPropagation()
                        show(index)
                    }}>
                        <Image src={src} style={{ width: '100%', height: '100%' }} mode='aspectFill' />
                        {
                            editable && !props.value &&
                            <View onClick={e => {
                                e.stopPropagation()
                                del(index)
                            }} style={Object.assign({}, styles.del_img_container, delIconStyle)}>
                                <Image src={delIcon ? delIcon : icon_del_image} mode='aspectFit' style={{ width: '100%', height: '100%' }} />
                            </View>
                        }
                    </View>
                )
            }





        React.useLayoutEffect(() => {
            setTimeout(() => {
                // console.log('asd', containerRef.current?.clientWidth)
                setSideLength(`calc((${containerRef.current?.clientWidth}px - ${spacingHorizontal} * 2 - ${spacingInner} * 2) / 3 - .1px)`)
            }, 350)
        }, [])


        if (props.value && props.value?.length > 0) {
            return (
                <View style={Object.assign({}, styles.container, props.style)} ref={containerRef}>
                    {props.value.map((item, index) => {
                        return <ItemView key={index} src={item} index={index} />
                    })}
                </View >
            )
        }

        return (
            <View style={Object.assign({}, styles.container, props.style)} ref={containerRef}>
                {viewModel?.photos instanceof Array && viewModel.photos.map((item, index) => {
                    return <ItemView key={index} src={typeof item === 'string' ? item : item.path} index={index} />
                })}

                {
                    !(viewModel?.photos?.length == maxCount) && editable && (
                        <View style={Object.assign({}, styles.item_container, {
                            marginTop: (viewModel?.photos?.length || 0) >= 3 ? spacingInner : 0,
                            marginLeft: (viewModel?.photos?.length || 0) % 3 == 0 ? spacingHorizontal : spacingInner,
                            width: sideLength,
                            height: sideLength,
                        }, addIconContainerStyle)} onClick={() => add()}>
                            <Image src={addIcon ? addIcon : icon_add_image} style={Object.assign({ width: '25%', height: '25%' }, addIconStyle)} mode='aspectFit' />
                            {props.addText && <Text style={Object.assign({ fontSize: '12px', color: 'lightgrey', marginTop: '2px' }, props.addTextStyle)}>{props.addText}</Text>}
                        </View>

                    )
                }
            </View >

        )



    }








const styles: Record<string, React.CSSProperties> = {
    container: {
        flexGrow: 1,
        minHeight: '.1px',
        backgroundColor: 'transparent',
        display: 'flex',
        flexDirection: 'row',
        flexWrap: 'wrap',
        borderRadius: '10px',
        // backgroundColor: 'red',
    },
    item_container: {
        overflow: 'hidden',
        borderRadius: '5px',
        display: 'flex',
        position: 'relative',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#ededed',
        flexDirection: 'column'
    },

    del_img_container: {
        position: 'absolute',
        right: '2px',
        top: '2px',
        width: '24px',
        height: '24px'
    },
}










